package fuben;

import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BankService {
    Map<String, Account> accounts = new HashMap<>();
    List<TransactionRecord> transactionRecords = new ArrayList<>();
    BankService bankService = new BankService();
    //执行一条交易记录，并更新账户余额。同时，将该记录添加到交易日志列表中。
    public void executeTransaction(TransactionRecord record){
        Account account = accounts.get(record.getAccountNumber());
        account.setBalance(record.getPostBalance());
        transactionRecords.add(record);

    }
    //- 功能：导出指定账户在某个时间范围内的所有交易记录到CSV文件。
    //- CSV文件格式：交易时间，类型，金额，对方账户，交易后余额。
    //- 同时在控制台输出：该时间范围内的总收入和总支出。
    public void exportAuditLog(String accountNumber, LocalDateTime start, LocalDateTime end, String filePath){
          double totalIncome = 0;
          double totalExpense = 0;
          for (TransactionRecord record : transactionRecords) {
              if (record.getAccountNumber().equals(accountNumber)
                      && record.getTimestamp().isAfter(start)
                      && record.getTimestamp().isBefore(end)) {
                  if(TransactionType.DEPOSIT.equals(record.getType()) || TransactionType.TRANSFER_IN.equals(record.getType())){
                      totalIncome += record.getAmount();
                  }
                  if(TransactionType.WITHDRAWAL.equals(record.getType()) || TransactionType.TRANSFER_OUT.equals(record.getType())){
                      totalExpense += record.getAmount();
                  }
              }
          }
        FileWriter writer = null;
        try {
            writer = new FileWriter(filePath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try {
            writer.write("TransactionTime,Type,Amount,CounterpartyAccount,PostBalance\n");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        for (TransactionRecord record : transactionRecords) {
              if (record.getAccountNumber().equals(accountNumber)
                      && record.getTimestamp().isAfter(start)
                      && record.getTimestamp().isBefore(end)) {
                  try {
                      writer.write(record.getTimestamp() + ","
                              + record.getType() + ","
                              + record.getAmount() + ","
                              + record.getCounterpartyAccount() + ","
                              + record.getPostBalance() + "\n");
                  } catch (IOException e) {
                      throw new RuntimeException(e);
                  }
              }
          }
    }

}
